<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Cities;
use App\Models\FileUpload;
use App\Models\FilmTypeMaster;
use App\Models\MacroManagement;
use App\Models\MakeMaster;
use App\Models\ModelMaster;
use App\Models\PartMaster;
use App\Models\ProvinceMaster;
use App\Models\RegionMaster;
use App\Models\Roles;
use App\Models\Permissions;
use App\Models\RollMaster;
use App\Models\RollTransfer;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\IOFactory;

/*
 * 卷膜管理*/
class RollsTransferController extends Controller
{

    public function index(Request $request)
    {
        $user_id = session('admin.id');
        $user_type = session('admin.user_type');
        $page = [
            'page_name' => 'rolls',
            'title' => ts('DHGL'),
            /*'breadcrumb' => [
                [
                    'text' => ts('MANAGEPRODUCT'),
                    'url' => 'javascript:void(0)'
                ]
            ],*/
        ];
        $model = DB::table('roll_transfer as rt')
            ->leftJoin('roll_master as rm', 'rm.id', 'rt.roll_id')
            ->leftJoin('users as y', 'y.id', 'rt.transfer_by_user_id')
            ->leftJoin('users as x', 'x.id', 'rt.transfer_to_user_id')
            ->leftJoin('users as c', 'c.id', 'rt.created_by')
            ->leftJoin('users as ys', 'ys.id', 'y.creator_id')
            ->leftJoin('users as xs', 'xs.id', 'x.creator_id')
            ->select([
                'rt.*',
                    DB::raw('y.abbr as ygmsmc'),
                    DB::raw('x.abbr as xgmsmc'),
                    DB::raw('if(y.user_type=3, ys.abbr, y.abbr) as ysdmc'),
                    DB::raw('if(x.user_type=3, xs.abbr, x.abbr) as xsdmc'),
                'x.user_type as xuser_type',
                    'y.user_type as yuser_type',
                'c.abbr as czy', 'rm.roll_number',
                'rm.film_type_id']
            );
        $model = filterByColumns($model, ['rm.roll_number', 'y.abbr', 'x.abbr', 'c.abbr' ]);
        $model = filterByDateRange($model, 'rt.created_at');
        if ($request->input('status')!==null) {
            $status = (int) $request->input('status');
            $model = $model->where('rt.approved', $status);
        }
        /*
         * 如果用户为管理员 */
        if ($user_type == 1) {
            $model = $model->where('c.id', 1);
        } else {
            $model = $model->where(function ($query) use ($user_id) {
                $query->where('y.id', $user_id)
                    ->orWhere('y.creator_id', $user_id)
                    ->orWhere('x.id', $user_id)
                    ->orWhere('x.creator_id', $user_id);
                /*->orWhere('c.id', $user_id)
                ->orWhere('c.creator_id', $user_id);*/
            });
        }
        $model = $model->orderByDesc('rt.id');
        $data = $model->paginate(50);
        return view('admin.rolls-transfer.index', [
            'data'=>$data,
            'page' => $page,
        ]);
    }

    public function store(Request $request)
    {
        $admin_id = session('admin.id');
        $user_type = session('admin.user_type');


        $roll_number = trim($request->input('roll_number'));
        $transfer_by_user_id = (int) $request->input('ygmsid');
        $transfer_to_user_id = (int) $request->input('xgmsid');
        $xsdid = (int) $request->input('xsdid');
        $transfer_to_user_id = $transfer_to_user_id ?: $xsdid;
        $length = (int) $request->input('length');
        $note = trim($request->input('note'));
        $approved = 0;
        $created_by = session('admin.id');
        if ($length <= 0) {
            return back()->withInput()->with('trash', ['content'=>'调货申请长度 不能为空！', 'type'=>'error']);
        }
        if (empty($transfer_by_user_id)) {
            return back()->withInput()->with('trash', ['content'=>'发起方-购买商 不能为空！', 'type'=>'error']);
        }
        if (empty($transfer_to_user_id)) {
            return back()->withInput()->with('trash', ['content'=>'接收方-购买商 不能为空！', 'type'=>'error']);
        }
        if (empty($note)) {
            return back()->withInput()->with('trash', ['content'=>'调货说明 不能为空！', 'type'=>'error']);
        }
        DB::beginTransaction();
        try {
            $roll = getRollsMasterByRollNumber($roll_number);
            if (empty($roll->id)) {
                return back()->withInput()->with('trash', ['content'=>'卷号不存在！', 'type'=>'error']);
            }
            if (!empty($roll->deleted_at)) {
                return back()->withInput()->with('trash', ['content'=>'卷号已被删除！', 'type'=>'error']);
            }
            $rlen = getRlenV401($roll->roll_number, $transfer_by_user_id);
            if ($length > $rlen) {
                return back()->withInput()->with('trash', ['content'=>'调货长度超过允许最大长度：'.$rlen.'cm', 'type'=>'error']);
            }
            $e = addRollTransfer($roll->id, $transfer_by_user_id, $transfer_to_user_id, $length, $note);
            if (empty($e)) {
                DB::rollback();//数据库回滚
                return redirect()->back()->withInput()->with('trash', ['content'=>'服务器错误，请稍后重试！', 'type'=>'error']);
            }
            $e = minusRestlen($transfer_by_user_id, $roll->roll_number, $length);
            if (empty($e)) {
                DB::rollback();//数据库回滚
                return redirect()->back()->withInput()->with('trash', ['content'=>'服务器错误，请稍后重试！', 'type'=>'error']);
            }
            DB::commit();
        } catch (\Exception $exception){
            DB::rollback();//数据库回滚
            return redirect()->back()->withInput()->with('trash', ['content'=>'服务器错误，请稍后重试！', 'type'=>'error']);
        }
        $url = '/admin/rolls-transfer';
        if ($user_type != 2) {
            $url = '/admin/verify/transfer';
        }
        return redirect($url)->with('trash', ts('FQDHSUCCESS'));
    }


    public function create(Request $request)
    {
        $user_id = session('admin.id');
        $user_type = session('admin.user_type');
        $page = [
            'page_name' => 'rolls',
            'title' => ts('FAQIDIAOHUO'),
            'breadcrumb' => [
                [
                    'text' => ts('DHGL'),
                    'url' => 'javascript:void(0)'
                ]
            ],
        ];
        $data = new RollTransfer();
        return view('admin.rolls-transfer.create', [
            'data'=>$data,
            'page' => $page,
        ]);
    }

}
